package com.dianrui.operation.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;

import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RidePath;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RideStep;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkPath;
import com.amap.api.services.route.WalkRouteResult;
import com.amap.api.services.route.WalkStep;
import com.dianrui.operation.Constant;
import com.dianrui.operation.R;
import com.dianrui.operation.adapter.SecretProtocolAdapter;
import com.dianrui.operation.bean.Battery;
import com.dianrui.operation.bean.BikePointModel;
import com.dianrui.operation.bean.NearCar;
import com.dianrui.operation.util.JsonUtils;
import com.dianrui.operation.util.MyUtil;
import com.dianrui.operation.okhttp.XHttpRequest;
import com.dianrui.operation.util.SharedUtil;
import com.dianrui.operation.util.StringUtils;
import com.dianrui.operation.util.ToastUtil;
import com.dianrui.operation.util.Url;
import com.dianrui.operation.view.opertionzxing.activity.OpeationCaptureActivity;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.tbit.tbitblesdk.Bike.TbitBle;
import com.tbit.tbitblesdk.Bike.model.BikeState;
import com.tbit.tbitblesdk.Bike.services.command.callback.StateCallback;
import com.tbit.tbitblesdk.protocol.Packet;
import com.tbit.tbitblesdk.protocol.callback.PacketCallback;
import com.tbit.tbitblesdk.protocol.callback.ResultCallback;
import com.xiaoantech.sdk.XiaoanBleApiClient;
import com.xiaoantech.sdk.ble.model.Response;
import com.xiaoantech.sdk.listeners.BleCallback;
import com.xiaoantech.sdk.listeners.BleStateChangeListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 车辆调度
 * lzy
 */
public class VehicleSchedulingActivity extends BaseActivity implements AMapLocationListener,RouteSearch.OnRouteSearchListener {
    private String mTitles;
    private String mType;
    private String mNumber;
    private LatLng latLng;
    public String CUSTOMMARKER = "Markers";
    public AMapLocationClient mLocationClient;
    public AMapLocationClientOption mLocationOption = null;
    private List<BikePointModel> bikePointList = new ArrayList<>();
    private List<Battery> batteryList = new ArrayList<>();
    private List<NearCar> nearCarsList = new ArrayList<>();
    private boolean isFirstLoc = true;
    private double currentLatitude;
    private double currentLongitude;
    private Marker clickMaker;
    private AMap aMap;
    private List<LatLng> mAreaPoints = new ArrayList<>();
    private BluetoothAdapter mBlueadapter;
    private BitmapDescriptor bitDTimeoutCarEle;
    private BitmapDescriptor bitDOutsideCarEle;
    private BitmapDescriptor bitDIllearCarEle;
    private BitmapDescriptor bitD_NoStop;
    private XiaoanBleApiClient apiClient;
    private XiaoanBleApiClient.Builder builder;


    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.mapviews)
    MapView mapview;
    @BindView(R.id.device_name)
    EditText deviceName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapview.onCreate(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapview.onSaveInstanceState(outState);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_vehiclescheduling;
    }

    @Override
    public void initView() {
        TbitBle.initialize(VehicleSchedulingActivity.this, new SecretProtocolAdapter());
        mBlueadapter = BluetoothAdapter.getDefaultAdapter();
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                mTitles = bundle.getString("titles");
                mNumber = bundle.getString("number");
                mType = bundle.getString("type");
                title.setText(mTitles + "(" + mNumber + ")");
            }
        }
        if (aMap == null) {
            aMap = mapview.getMap();
        }
        builder = new XiaoanBleApiClient.Builder(this);
        apiClient = builder.build();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(VehicleSchedulingActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                startLocation();
            } else {
                ActivityCompat.requestPermissions(VehicleSchedulingActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            }
        } else {
            startLocation();
        }

        UiSettings mUiSettings = aMap.getUiSettings();
        mUiSettings.setTiltGesturesEnabled(false);
        mUiSettings.setRotateGesturesEnabled(false);
        mUiSettings.setZoomControlsEnabled(false);

        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);

        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。


        aMap.setOnMarkerClickListener(markerClickListener);
        aMap.setInfoWindowAdapter(infoWindowAdapter);
        aMap.setOnInfoWindowClickListener(listener);
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if (clickMaker != null && clickMaker.isInfoWindowShown()) {
                    clickMaker.hideInfoWindow();
                }
            }
        });
        aMap.setOnMapClickListener(listeners);

        deviceName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 10) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(deviceName.getWindowToken(), 0);
                    }
                }

            }
        });

        View timeoutView = LayoutInflater.from(VehicleSchedulingActivity.this).inflate(R.layout.timeout_point, null);

        bitDTimeoutCarEle = BitmapDescriptorFactory.fromView(timeoutView);

        View outsideView = LayoutInflater.from(VehicleSchedulingActivity.this).inflate(R.layout.outside_point, null);

        bitDOutsideCarEle = BitmapDescriptorFactory.fromView(outsideView);

        View illegalcarView = LayoutInflater.from(VehicleSchedulingActivity.this).inflate(R.layout.illegalcar_point, null);

        bitDIllearCarEle = BitmapDescriptorFactory.fromView(illegalcarView);

        View view1 = LayoutInflater.from(VehicleSchedulingActivity.this).inflate(R.layout.over_nostop_point, null);
        bitD_NoStop = BitmapDescriptorFactory.fromView(view1);
    }


    @OnClick({R.id.back, R.id.refresh, R.id.location, R.id.scans, R.id.startdefense_btn, R.id.withdrawdevice_btn, R.id.close_btn, R.id.oppacc_btn, R.id.bigger, R.id.smaller, R.id.play_btn, R.id.gps_btn, R.id.device_restart, R.id.malfunction_btn, R.id.llegal_btn})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.refresh:
                if (currentLatitude == 0.0000 && currentLongitude == 0.0000) {
                    return;
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(VehicleSchedulingActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
                                aMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(currentLatitude, currentLongitude)));
                            }
                        }, 500);
                    } else {
                        ActivityCompat.requestPermissions(VehicleSchedulingActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 3);
                    }
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
                            aMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(currentLatitude, currentLongitude)));
                        }
                    }, 500);
                }
                break;

            case R.id.location:
                if (currentLatitude == 0.0000 && currentLongitude == 0.0000) {
                    return;
                }
                //getStation(latLng);
                getRfreshNearCar(latLng);
                break;

            case R.id.scans:
                if (Build.VERSION.SDK_INT >= 23) {
                    if (ContextCompat.checkSelfPermission(VehicleSchedulingActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        Intent intent = new Intent(VehicleSchedulingActivity.this, OpeationCaptureActivity.class);
                        intent.putExtra("camflag", "1");
                        startActivityForResult(intent, 102);
                    } else {
                        ActivityCompat.requestPermissions(VehicleSchedulingActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                    }
                } else {
                    Intent intent = new Intent(VehicleSchedulingActivity.this, OpeationCaptureActivity.class);
                    intent.putExtra("camflag", "1");
                    startActivityForResult(intent, 102);
                }
                break;
            case R.id.startdefense_btn://启动
                if (StringUtils.isEmpty(deviceName.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_device_number_error));
                } else {
                    sendCommand(deviceName.getText().toString(), "1", "2", "1");
                }
                break;

            case R.id.withdrawdevice_btn://撤防
                if (StringUtils.isEmpty(deviceName.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_device_number_error));
                } else {
                    sendCommand(deviceName.getText().toString(), "0", "3", "2");
                }
                break;

            case R.id.close_btn://关闭
                if (StringUtils.isEmpty(deviceName.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_device_number_error));
                } else {
                    sendCommand(deviceName.getText().toString(), "0", "2", "3");
                }
                break;

            case R.id.oppacc_btn://开仓
                if (StringUtils.isEmpty(deviceName.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_device_number_error));
                } else {
                    sendCommand(deviceName.getText().toString(), "0", "5", "4");
                }
                break;

            case R.id.play_btn://播报
                if (StringUtils.isEmpty(deviceName.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_device_number_error));
                } else {
                    sendCommand(deviceName.getText().toString(), "0", "1", "5");
                }
                break;

            case R.id.gps_btn://GPS重启
                if (StringUtils.isEmpty(deviceName.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_device_number_error));
                } else {
                    sendCommand(deviceName.getText().toString(), "0", "9", "");
                }
                break;

            case R.id.device_restart://设备重启
                if (StringUtils.isEmpty(deviceName.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_device_number_error));
                } else {
                    sendCommand(deviceName.getText().toString(), "0", "8", "");
                }
                break;

            case R.id.malfunction_btn:
                if (StringUtils.isEmpty(deviceName.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_device_number_error));
                } else {
                    Intent intent = new Intent(VehicleSchedulingActivity.this, TroubleCarActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("carnumber", deviceName.getText().toString());
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
                break;

            case R.id.llegal_btn:
                if (StringUtils.isEmpty(deviceName.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_device_number_error));
                } else {
                    Intent intent = new Intent(VehicleSchedulingActivity.this, BreakRuleActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("carnumber", deviceName.getText().toString());
                    intent.putExtras(bundle);
                    startActivity(intent);

                }
                break;

            case R.id.bigger:
                MyUtil.setMapStatus(mapview, MyUtil.getZoom(mapview) - 1);
                break;
            case R.id.smaller:
                MyUtil.setMapStatus(mapview, MyUtil.getZoom(mapview) + 1);
                break;

            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapview.onDestroy();
        if (null != mLocationClient) {
            mLocationClient.onDestroy();
            mLocationClient.stopLocation();
            mLocationClient = null;
        }

        bitDIllearCarEle.recycle();
        bitDTimeoutCarEle.recycle();
        bitDOutsideCarEle.recycle();
        bitD_NoStop.recycle();
        TbitBle.destroy();
        TbitBle.disConnect();
        if (apiClient != null) {
            apiClient.disConnect();
            apiClient.onDestroy();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapview.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapview.onPause();
    }


    //获取网点
    private void getStation(LatLng latLng) {
        JsonObject networksJsonobject = new JsonObject();
        networksJsonobject.addProperty("type_id", "2");
        networksJsonobject.addProperty("gps", latLng.longitude + "," + latLng.latitude);
        networksJsonobject.addProperty("radius", "0");//周边范围：默认1公里或者0公里,
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.GETNETWORK_BIKE, networksJsonobject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (bikePointList != null) {
                                bikePointList.clear();
                            }
                            if (mAreaPoints != null) {
                                mAreaPoints.clear();
                            }
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                JSONObject jsonObject2 = jsonObject.optJSONObject("area");
                                if (jsonObject.optString("data").equals("{}")) {
                                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentLatitude, currentLongitude), 14));
                                } else if (jsonObject.optString("data").equals("[]")) {
                                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentLatitude, currentLongitude), 14));
                                } else {
                                    JSONArray gfixedPath = jsonObject.optJSONObject("area").optJSONArray("gfixed_path");
                                    if (gfixedPath.length() > 0) {
                                        for (int j = 0; j < gfixedPath.length(); j++) {
                                            JSONObject jsonObject3 = gfixedPath.optJSONObject(j);
                                            mAreaPoints.add(new LatLng(jsonObject3.optDouble("lat"), jsonObject3.optDouble("lng")));
                                        }
                                        if (mAreaPoints.size() > 0) {
                                            PolygonOptions polygonOptions = new PolygonOptions();
                                            polygonOptions.addAll(mAreaPoints);
                                            polygonOptions.strokeWidth(4);
                                            polygonOptions.strokeColor(Color.rgb(255, 0, 0));
                                            polygonOptions.fillColor(Color.argb(0, 0, 0, 0));
                                            aMap.addPolygon(polygonOptions);
                                        }
                                        LatLngBounds.Builder b = LatLngBounds.builder();

                                        for (LatLng latLng : mAreaPoints) {
                                            b.include(latLng);
                                        }
                                        LatLngBounds bounds = b.build();
                                        aMap.moveCamera(CameraUpdateFactory.newLatLngBoundsRect(bounds, 130, 130, 580, 260));
                                    }

                                }
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        BikePointModel bikeModel = new BikePointModel();
                                        bikeModel.glat = jsonArray.optJSONObject(i).optDouble("glat");
                                        bikeModel.glng = jsonArray.optJSONObject(i).optDouble("glng");
                                        bikeModel.vehicle_number = jsonArray.optJSONObject(i).optString("vehicle_number");
                                        bikePointList.add(bikeModel);

                                        if ("1".equals(jsonArray.optJSONObject(i).optString("fixed_type"))) {
                                            List<LatLng> points = new ArrayList<>();
                                            if (points != null) {
                                                points.clear();
                                            }
                                            JSONArray jsonArray3 = jsonArray.optJSONObject(i).optJSONArray("fixed_path");
                                            if (jsonArray3.length() > 0) {
                                                for (int j = 0; j <= jsonArray3.length(); j++) {
                                                    if (j == jsonArray3.length()) {
                                                        JSONObject jsonObject1 = jsonArray3.optJSONObject(0);
                                                        points.add(new LatLng(jsonObject1.optDouble("lat"), jsonObject1.optDouble("lng")));
                                                    } else {
                                                        JSONObject jsonObject1 = jsonArray3.optJSONObject(j);
                                                        points.add(new LatLng(jsonObject1.optDouble("lat"), jsonObject1.optDouble("lng")));
                                                    }
                                                }

                                                if (points.size() < 2) {
                                                    return;
                                                }
                                                if (jsonArray.optJSONObject(i).optString("is_forbid").equals("1")) {
                                                    aMap.addPolyline((new PolylineOptions()).addAll(points)
                                                            .width(4).setDottedLine(true).color(Color.RED));
                                                    MarkerOptions markerOptions1 = new MarkerOptions();
                                                    markerOptions1.position(new LatLng(bikePointList.get(i).glat, bikePointList.get(i).glng)).icon(bitD_NoStop);
                                                    Marker marker = aMap.addMarker(markerOptions1);


                                                } else {
                                                    List<BitmapDescriptor> textureList = new ArrayList<>();
                                                    textureList.add(BitmapDescriptorFactory.fromResource(R.mipmap.customer_img));

                                                    List<Integer> textureIndexs = new ArrayList<>();
                                                    textureIndexs.add(i);
                                                    List<LatLng> overLatlngList = new ArrayList<>(points);

                                                    PolylineOptions polylineOptions = new PolylineOptions();
                                                    polylineOptions.addAll(overLatlngList);
                                                    polylineOptions.width(4);
                                                    polylineOptions.setCustomTextureList(textureList);
                                                    polylineOptions.setCustomTextureIndex(textureIndexs);
                                                    polylineOptions.setDottedLine(true);
                                                    polylineOptions.setUseTexture(true);
                                                    aMap.addPolyline(polylineOptions);
                                                }
                                            }


                                        } else if ("0".equals(jsonArray.optJSONObject(i).optString("fixed_type"))) {
                                            int networkRange = jsonArray.optJSONObject(i).optInt("network_range");
                                            aMap.addCircle(new CircleOptions()
                                                    .center(new LatLng(bikePointList.get(i).glat, bikePointList.get(i).glng))
                                                    .radius(networkRange)
                                                    .fillColor(Color.argb(46, 64, 194, 134)).strokeWidth(4).strokeColor(Color.argb(46, 64, 194, 134)));
                                        }
                                    }

                                }
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                spUtils.clear();
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });

    }

    //获取附近的车
    private void getNearCar(LatLng latLng) {
        JsonObject nearJsonobject = new JsonObject();
        nearJsonobject.addProperty("type_id", "2");
        nearJsonobject.addProperty("type", mType);
        nearJsonobject.addProperty("gps", latLng.longitude + "," + latLng.latitude);
        nearJsonobject.addProperty("radius", "0");
        nearJsonobject.addProperty("status", "4,5,6");
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.NEARBIKE, nearJsonobject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        if (isFinishing()) {
                            return;
                        }
                        String status = JsonUtils.getJsonStr(result, Constant.STATUS);
                        if (Constant.DATASUCCESS.equals(status)) {
                            String data = JsonUtils.getJsonStr(result, "data");
                            if (nearCarsList != null) {
                                nearCarsList.clear();
                            }
                            if (!StringUtils.isEmpty(data)) {
                                List<NearCar> nearCarsLists = JsonUtils.jsonStrToList(data, new TypeToken<ArrayList<NearCar>>() {
                                }.getType());
                                if (nearCarsLists != null && nearCarsLists.size() > 0) {
                                    nearCarsList.addAll(nearCarsLists);
                                }

                                for (int i = 0; i < nearCarsList.size(); i++) {
                                    if ("8".equals(nearCarsList.get(i).getVehicle_status())) {
                                        MarkerOptions markerOptions = new MarkerOptions();
                                        markerOptions.position(new LatLng(nearCarsList.get(i).getGlat(), nearCarsList.get(i).getGlng()));
                                        markerOptions.icon(bitDIllearCarEle);
                                        Marker marker = aMap.addMarker(markerOptions);
                                        marker.setTitle(CUSTOMMARKER);
                                        marker.setObject(nearCarsList.get(i));
                                    }

                                    if ("7".equals(nearCarsList.get(i).getVehicle_status())) {
                                        MarkerOptions markerOptions = new MarkerOptions();
                                        markerOptions.position(new LatLng(nearCarsList.get(i).getGlat(), nearCarsList.get(i).getGlng()));
                                        markerOptions.icon(bitDTimeoutCarEle);
                                        Marker marker = aMap.addMarker(markerOptions);
                                        marker.setTitle(CUSTOMMARKER);
                                        marker.setObject(nearCarsList.get(i));
                                    }

                                    if ("6".equals(nearCarsList.get(i).getVehicle_status())) {
                                        MarkerOptions markerOptions = new MarkerOptions();
                                        markerOptions.position(new LatLng(nearCarsList.get(i).getGlat(), nearCarsList.get(i).getGlng()));
                                        markerOptions.icon(bitDOutsideCarEle);
                                        Marker marker = aMap.addMarker(markerOptions);
                                        marker.setTitle(CUSTOMMARKER);
                                        marker.setObject(nearCarsList.get(i));

                                    }
                                }
                            }
                        } else if ("1001".equals(status)) {
                            ToastUtil.showToast(JsonUtils.getJsonStr(result, "message"));
                        } else if ("1002".equals(status)) {
                            spUtils.clear();
                            ToastUtil.showToast(JsonUtils.getJsonStr(result, "message"));
                            JumpActivitys(LoginActivity.class);
                            finish();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });

    }


    //刷新附近的车辆
    private void getRfreshNearCar(LatLng latLng) {
        showLoadingDialog("正在刷新");
        JsonObject nearJsonobject = new JsonObject();
        nearJsonobject.addProperty("type_id", "2");
        nearJsonobject.addProperty("type", mType);
        nearJsonobject.addProperty("gps", latLng.longitude + "," + latLng.latitude);
        nearJsonobject.addProperty("radius", "0");
        nearJsonobject.addProperty("status", "4,5,6");
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.NEARBIKE, nearJsonobject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        if (isFinishing()) {
                            return;
                        }
                        String status = JsonUtils.getJsonStr(result, Constant.STATUS);
                        if (Constant.DATASUCCESS.equals(status)) {
                            dismissLoadingDialog();
                            String data = JsonUtils.getJsonStr(result, "data");
                            if (nearCarsList != null) {
                                nearCarsList.clear();
                            }
                            if (!StringUtils.isEmpty(data)) {
                                List<NearCar> nearCarsLists = JsonUtils.jsonStrToList(data, new TypeToken<ArrayList<NearCar>>() {
                                }.getType());
                                if (nearCarsLists != null && nearCarsLists.size() > 0) {
                                    nearCarsList.addAll(nearCarsLists);
                                }

                                for (int i = 0; i < nearCarsList.size(); i++) {
                                    if ("8".equals(nearCarsList.get(i).getVehicle_status())) {
                                        MarkerOptions markerOptions = new MarkerOptions();
                                        markerOptions.position(new LatLng(nearCarsList.get(i).getGlat(), nearCarsList.get(i).getGlng()));
                                        markerOptions.icon(bitDIllearCarEle);
                                        Marker marker = aMap.addMarker(markerOptions);
                                        marker.setTitle(CUSTOMMARKER);
                                        marker.setObject(nearCarsList.get(i));
                                    }

                                    if ("7".equals(nearCarsList.get(i).getVehicle_status())) {
                                        MarkerOptions markerOptions = new MarkerOptions();
                                        markerOptions.position(new LatLng(nearCarsList.get(i).getGlat(), nearCarsList.get(i).getGlng()));
                                        markerOptions.icon(bitDTimeoutCarEle);
                                        Marker marker = aMap.addMarker(markerOptions);
                                        marker.setTitle(CUSTOMMARKER);
                                        marker.setObject(nearCarsList.get(i));
                                    }

                                    if ("6".equals(nearCarsList.get(i).getVehicle_status())) {
                                        MarkerOptions markerOptions = new MarkerOptions();
                                        markerOptions.position(new LatLng(nearCarsList.get(i).getGlat(), nearCarsList.get(i).getGlng()));
                                        markerOptions.icon(bitDOutsideCarEle);
                                        Marker marker = aMap.addMarker(markerOptions);
                                        marker.setTitle(CUSTOMMARKER);
                                        marker.setObject(nearCarsList.get(i));

                                    }
                                }
                            }
                        } else if ("1001".equals(status)) {
                            ToastUtil.showToast(JsonUtils.getJsonStr(result, "message"));
                        } else if ("1002".equals(status)) {
                            spUtils.clear();
                            ToastUtil.showToast(JsonUtils.getJsonStr(result, "message"));
                            JumpActivitys(LoginActivity.class);
                            finish();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });

    }

    //开始定位
    private void startLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为Hight_Accuracy高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }


    @Override
    public void initData() {}

    //按完成
    private void batteryFinish(final String number) {
        showLoadingDialog("请稍候...");
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("number", number);
        jsonObject.addProperty("sw", "1");
        jsonObject.addProperty("type", "5");
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.QUERYVEHCLES, jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                getRfreshNearCar(latLng);
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }


    // 定义 Marker 点击事件监听
    AMap.OnMarkerClickListener markerClickListener = new AMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(final Marker marker) {
            clickMaker = marker;
            marker.showInfoWindow();
            return true;
        }
    };

    AMap.InfoWindowAdapter infoWindowAdapter = new AMap.InfoWindowAdapter() {
        @SuppressLint("SetTextI18n")
        @Override
        public View getInfoWindow(Marker marker) {
            View view = LayoutInflater.from(VehicleSchedulingActivity.this).inflate(R.layout.inspection_bubble, null);
            final TextView number = view.findViewById(R.id.number);
            TextView carstatus = view.findViewById(R.id.carstatus);
            TextView battery = view.findViewById(R.id.battery);
            TextView rssi = view.findViewById(R.id.rssi);
            TextView carlocation = view.findViewById(R.id.carlocations);
            Button malfunction = view.findViewById(R.id.malfunction_btn);//故障车
            Button llegal = view.findViewById(R.id.llegal_btn);//违章车
            Button startdefense = view.findViewById(R.id.startdefense_btn);
            Button withdrawdevice = view.findViewById(R.id.withdrawdevice_btn);
            Button closedevice = view.findViewById(R.id.close_btn);
            Button oppacc = view.findViewById(R.id.oppacc_btn);
            Button playBtn = view.findViewById(R.id.play_btn);
            Button gpsBtn = view.findViewById(R.id.gps_btn);
            Button deviceRestart = view.findViewById(R.id.device_restart);
            Button nav = view.findViewById(R.id.nav_btn);
            final NearCar info = (NearCar) marker.getObject();
            number.setText("车辆编号: " + info.getNumber());

            battery.setText("电量: " + info.getBattery() + "%");

            carstatus.setText("车辆状态: " + info.getStatus_name());

            rssi.setText("信号强度：" + info.getRssi());

            StringBuilder locationiString = new StringBuilder();
            locationiString.append("车辆地址：").append(info.getCity_path());
            if (!StringUtils.isEmpty(info.getCity_path())) {
                carlocation.setText(locationiString.toString());
            } else {
                carlocation.setText("车辆地址：无");
            }
            malfunction.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (info.getMaintain_id() > 0) {
                        Intent intent = new Intent(VehicleSchedulingActivity.this, FaultDetailsActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putInt("maintain_id", info.getMaintain_id());
                        intent.putExtras(bundle);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(VehicleSchedulingActivity.this, TroubleInfoCarActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("carnumber", info.getNumber());
                        bundle.putString("address", info.getCity_path());
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                }
            });
            llegal.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (info.getViolation_id() > 0) {
                        Intent intent = new Intent(VehicleSchedulingActivity.this, ViolationDetailsActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putInt("violation_id", info.getViolation_id());
                        intent.putExtras(bundle);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(VehicleSchedulingActivity.this, BreakRuleInfoActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("carnumber", info.getNumber());
                        bundle.putString("address", info.getCity_path());
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                }
            });

            startdefense.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendCommand(info.getNumber(), "1", "2", "1");
                }
            });
            withdrawdevice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendCommand(info.getNumber(), "0", "3", "2");
                }
            });
            closedevice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendCommand(info.getNumber(), "0", "2", "3");
                }
            });
            oppacc.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendCommand(info.getNumber(), "0", "5", "4");
                }
            });
            playBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendCommand(info.getNumber(), "0", "1", "5");
                }
            });
            gpsBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendCommand(info.getNumber(), "0", "9", "");
                }
            });

            deviceRestart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendCommand(info.getNumber(), "0", "8", "");

                }
            });
            nav.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(VehicleSchedulingActivity.this, AMapNaviActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putDouble("currentLat", currentLatitude);
                    bundle.putDouble("currentLng", currentLongitude);
                    bundle.putDouble("targetLat", info.glat);
                    bundle.putDouble("targetLng", info.glng);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            });
            return view;
        }

        @Override
        public View getInfoContents(Marker marker) {
            return null;
        }
    };

    //点击marker就消失
    AMap.OnInfoWindowClickListener listener = new AMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
            marker.hideInfoWindow();
        }
    };

    final AMap.OnMapClickListener listeners = new AMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {
            clickMaker.hideInfoWindow();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 102) {
            String imel = data.getStringExtra("IMEI");
            if (!StringUtils.isEmpty(imel)) {
                deviceName.setText(imel);
            }

        }
    }

    //高德地图定位回调
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            currentLatitude = aMapLocation.getLatitude();
            currentLongitude = aMapLocation.getLongitude();
            if (isFirstLoc) {
                latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                getStation(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()));
                if (mType.equals("7")) {
                }else {
                    getNearCar(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()));
                }
                isFirstLoc = false;
            }
        }
    }

    /**
     * 统一下发指令,第一参数是车辆编号，第二个开关,第三个是什么类型指令，第四个是蓝牙命令类型
     * @param number          车辆编号
     * @param sw              开关：（电门：1开启，0关闭）（设防：1设防，0撤防）（电机锁：1上锁，0解锁）（电池锁：1完成，0开仓）；默认0
     * @param type            1寻车，2电门开关，3设防撤防，4电机锁，5电池锁，6刷新定位，7查看定位，8设备重启，9GPS信号重启
     * @param blueCommandType 蓝牙命令类型
     */
    private void sendCommand(final String number, final String sw, final String type, final String blueCommandType) {
        showLoadingDialog("正在下发命令...");
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("number", number);
        jsonObject.addProperty("sw", sw);
        jsonObject.addProperty("type", type);
        jsonObject.addProperty("is_bluetooth", "0");
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.QUERYVEHCLES, jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    dismissLoadingDialog();
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                if (jsonObject.optString("data").equals("{}")) {
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                } else {
                                    showBlueTeethDialog(jsonObject, number, blueCommandType);
                                }
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    private void showBlueTeethDialog(final JSONObject jsonObject, final String number, final String blueCommandType) {
        AlertDialog.Builder builder = new AlertDialog.Builder(VehicleSchedulingActivity.this, R.style.activity_dialog);
        View view = LayoutInflater.from(VehicleSchedulingActivity.this).inflate(R.layout.blue_endcar_dialog, null);
        final AlertDialog conituredialog = builder.create();
        conituredialog.setView(view);
        conituredialog.show();
        final TextView contents = view.findViewById(R.id.content);
        final Button endCarstartCars = view.findViewById(R.id.start_cars);
        final Button cancel = view.findViewById(R.id.cancel);
        contents.setText(jsonObject.optString("message"));
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                conituredialog.dismiss();
            }
        });
        endCarstartCars.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                conituredialog.dismiss();
                if (!mBlueadapter.isEnabled()) {
                    startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                    ToastUtil.showToast(getString(R.string.please_open_blueteeth));
                } else {
                    connectBlueTeeth(number, jsonObject.optJSONObject("data").optString("device"), jsonObject.optJSONObject("data").optString("token"), blueCommandType);
                }

            }
        });
    }


    //蓝牙连接，第一个参数暂时无用，第二个设备编号，第三个密钥，第四个作为不同功能指令区分
    private void connectBlueTeeth(final String number, String devices, String token, final String blueCommandType) {
        showLoadingDialog("正在连接蓝牙中");
        TbitBle.connect(devices, token, new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                // 连接回应
                if (resultCode == 0) {//启动
                    if (blueCommandType.equals("1")) {
                        unlockDevice(number);
                    } else if (blueCommandType.equals("2")) {//撤防
                        defenseCloseBlueteethDevice(number);
                    } else if (blueCommandType.equals("3")) {//关闭
                        defenseBlueteethDevice(number);
                    } else if (blueCommandType.equals("4")) {//开仓
                        openAccBlueteethDevice(number);
                    } else if (blueCommandType.equals("5")) {//播报
                        findCarBlueteethDevice(number);
                    }
                } else {
                    dismissLoadingDialog();
                    ToastUtil.showToast(" 蓝牙连接失败，请重新再试");
                }
            }
        }, new StateCallback() {
            @Override
            public void onStateUpdated(BikeState bikeState) {

            }
        });
    }

    private void openAccBlueteethDevice(final String number) {
        TbitBle.commonCommand((byte) 0x03, (byte) 0x05, new Byte[]{0x01},
                new ResultCallback() {
                    @Override
                    public void onResult(int resultCode) {
                        // 发送状态回复
                        dismissLoadingDialog();
                        if (resultCode == 0) {
                            sendCommandWithTibtleBlueTeeth(number, "0", "5");
                        } else {
                            ToastUtil.showToast("蓝牙操作失败，请稍候再试");
                        }
                    }
                }, new PacketCallback() {
                    @Override
                    public void onPacketReceived(Packet packet) {
                        // 收到packet回复
                    }
                });

    }

    private void findCarBlueteethDevice(final String number) {
        TbitBle.commonCommand((byte) 0x03, (byte) 0x04, new Byte[]{0x01},
                new ResultCallback() {
                    @Override
                    public void onResult(int resultCode) {
                        // 发送状态回复
                        dismissLoadingDialog();
                        if (resultCode == 0) {
                            sendCommandWithTibtleBlueTeeth(number, "0", "1");
                        } else {
                            ToastUtil.showToast("蓝牙操作失败，请稍候再试");
                        }
                    }
                }, new PacketCallback() {
                    @Override
                    public void onPacketReceived(Packet packet) {
                        // 收到packet回复
                    }
                });

    }

    // 解锁
    private void unlockDevice(final String number) {
        TbitBle.unlock(new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                dismissLoadingDialog();
                // 解锁回应
                if (resultCode==0){
                    sendCommandWithTibtleBlueTeeth(number, "1", "2");
                }else {
                    ToastUtil.showToast("蓝牙操作失败,请稍候再试");
                }

            }
        });
    }


    //设防开启蓝牙命令
    private void defenseBlueteethDevice(final String number) {
        TbitBle.commonCommand((byte) 0x03, (byte) 0x01, new Byte[]{0x01}, new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                // 发送状态回复
                dismissLoadingDialog();
                if (resultCode == 0) {
                    ToastUtil.showToast("发送蓝牙指令成功");
                    sendCommandWithTibtleBlueTeeth(number, "0", "2");
                } else {
                    ToastUtil.showToast("蓝牙指令失败，请重新再试");
                }
            }
        }, new PacketCallback() {
            @Override
            public void onPacketReceived(Packet packet) {
                // 收到packet回复
            }
        });

    }


    //撤防蓝牙命令
    private void defenseCloseBlueteethDevice(final String number) {
        TbitBle.commonCommand((byte) 0x03, (byte) 0x01, new Byte[]{0x00}, new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                dismissLoadingDialog();
                if (resultCode == 0) {
                    ToastUtil.showToast("发送蓝牙指令成功");
                    sendCommandWithTibtleBlueTeeth(number, "0", "3");
                } else {
                    ToastUtil.showToast("蓝牙指令失败，请重新再试");
                }
            }
        }, new PacketCallback() {
            @Override
            public void onPacketReceived(Packet packet) {
            }
        });

    }

    private void sendCommandWithTibtleBlueTeeth(String number, String sw, String type) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("number", number);
        jsonObject.addProperty("sw", sw);
        jsonObject.addProperty("type", type);
        jsonObject.addProperty("is_bluetooth", "1");
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.QUERYVEHCLES, jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    dismissLoadingDialog();
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    public void connectXiaoAnBlueTeeth(final String number, String imei, final String xaCommandType) {
        showLoadingDialog("正在连接蓝牙中");
        if (null != apiClient) {
            apiClient.connectToIMEI(imei);
        }
        builder.setBleStateChangeListener(new BleStateChangeListener() {
            @Override
            public void onConnect(BluetoothDevice bluetoothDevice) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("蓝牙连接成功", "蓝牙连接成功");
                        if (xaCommandType.equals("1")) {//启动
                            setAcc(number);
                        } else if (xaCommandType.equals("2")) {//撤防
                            setundefend(number);
                        } else if (xaCommandType.equals("3")) {//关闭
                            setAccOff(number);
                        } else if (xaCommandType.equals("4")) {//开仓
                            setsaddle(number);
                        } else if (xaCommandType.equals("5")) {//播放
                            findcar(number);
                        }
                    }
                });
            }
            @Override
            public void onDisConnect(BluetoothDevice bluetoothDevice) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoadingDialog();
                        Log.e("蓝牙连接失败", "蓝牙连接失败");
                        ToastUtil.showToast("蓝牙连接失败,请重新连接 ");
                    }
                });
            }

            @Override
            public void onDeviceReady(BluetoothDevice bluetoothDevice) {}

            @Override
            public void onReadRemoteRssi(int i) { }

            @Override
            public void onError(BluetoothDevice bluetoothDevice, String s, int i) {}

            @Override
            public void onBleAdapterStateChanged(int i) {}
        });
    }

    //小安寻车
    public void findcar(final String number) {
        apiClient.findCar(new BleCallback() {
            @Override
            public void onResponse(Response response) {
                dismissLoadingDialog();
                if (response.code==0) {
                    sendCommandWithTibtleBlueTeeth(number, "0", "1");
                }else {
                    ToastUtil.showToast("蓝牙操作失败,请重新连接");
                }
            }
        });
    }

    //小安撤防
    public void setundefend(final String number) {
        apiClient.setDefend(false, new BleCallback() {
            @Override
            public void onResponse(final Response response) {
                dismissLoadingDialog();
                if (response.code==0) {
                    sendCommandWithTibtleBlueTeeth(number, "0", "3");
                }else {
                    ToastUtil.showToast("蓝牙操作失败，请重新再试");
                }

            }
        });
    }


    //小安电池仓开
    public void setsaddle(final String number) {
        apiClient.setSaddle(true, new BleCallback() {
            @Override
            public void onResponse(Response response) {
                dismissLoadingDialog();
                if (response.code==0) {
                    sendCommandWithTibtleBlueTeeth(number, "0", "5");
                }else {
                    ToastUtil.showToast("蓝牙操作失败，请重新再试");
                }
            }
        });
    }

    //小安电池仓关
    public void setsaddleoff() {
        apiClient.setSaddle(false, new BleCallback() {
            @Override
            public void onResponse(Response response) {
                Log.e("saddle: ", response.toString());
            }
        });
    }

    //小安电门开
    public void setAcc(final String number) {
        apiClient.setAcc(true, new BleCallback() {
            @Override
            public void onResponse(Response response) {
                dismissLoadingDialog();
                if (response.code==0) {
                    sendCommandWithTibtleBlueTeeth(number, "1", "2");
                }else {
                    ToastUtil.showToast("蓝牙操作失败，请重新再试");
                }
            }
        });
    }

    //小安电门关
    public void setAccOff(final String number) {
        apiClient.setAcc(false, new BleCallback() {
            @Override
            public void onResponse(Response response) {
                dismissLoadingDialog();
                if (response.code==0) {
                    sendCommandWithTibtleBlueTeeth(number, "0", "2");
                }else {
                    ToastUtil.showToast("蓝牙操作失败，请重新再试");
                }
            }
        });
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {}

    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {}

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {}

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {}
}
